package com.yupi.springbootinit.datasource;


import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.rholder.retry.Retryer;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.entity.Video;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.HttpCookie;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class VideoDataSourceImpl implements DataSource<Video> {

    @Resource
    private Retryer<String> retryer;


    @Override
    public Page<Video> doSearch(String searchText, long pageNum, long pageSize) {
        String url1 = "https://www.bilibili.com";
        String url2 = String.format("https://api.bilibili.com/x/web-interface/search/type?search_type=video&keyword=%s&order=click", searchText);
        HttpCookie cookie = HttpRequest.get(url1).execute().getCookie("buvid3");
        String body = null;
        try {
            body = retryer.call(() -> HttpRequest.get(url2)
                    .cookie(cookie)
                    .execute().body());
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "重试失败");
        }
        Map<String, Object> map = JSONUtil.toBean(body, Map.class);
        Map dataMap = (Map) map.get("data");
        Page<Video> videoPage = new Page<>(pageNum, pageSize);
        List<Video> videoList = new ArrayList<>();
        JSONArray dataArray = (JSONArray) dataMap.get("result");
        for (Object o : dataArray) {
            JSONObject jsonObject = (JSONObject) o;
            String src = (String) jsonObject.get("arcurl");
            String title=(String) jsonObject.get("title");
            String pic ="http:"+(String) jsonObject.get("pic");
            String author =(String) jsonObject.get("author");
            Video video =new Video();
            video.setPic(pic);
            video.setTitle(title);
            video.setSrc(src);
            video.setAuthor(author);
            videoList.add(video);
            if(videoList.size()>=8){
                break;
            }
        }
        videoPage.setRecords(videoList);
        return videoPage;
    }
}
